package cn.edu.sasu.webservice.impl;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;
import cn.edu.sasu.domain.Weather;
import cn.edu.sasu.utils.WeatherUtil;
import cn.edu.sasu.webservice.NewsService;

public class NewsServiceImpl implements NewsService {
	private WeatherUtil weatherUtil = null;

	public NewsServiceImpl() {

		weatherUtil = new WeatherUtil();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.sasu.webservice.impl.NewsService#getCCityCode()
	 */
	@Override
	public String getCCityCode() throws Exception {
		String scode = getSCityCode();
		String ccode = "";

		String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getSupportCityString?theRegionCode="
				+ scode;
		HttpURLConnection connection = (HttpURLConnection) new java.net.URL(url)
				.openConnection();

		connection.setRequestMethod("GET");
		connection.setDoInput(true);
		connection.setDoOutput(true);

		connection.setDoInput(true);
		connection.setDoOutput(true);

		if (connection.getResponseCode() == 200) {
			InputStream inStream = connection.getInputStream();

			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(inStream, "UTF-8");
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {
				case XmlPullParser.START_TAG:
					if ("string".equals(parser.getName())) {
						String text = parser.nextText();
						if (text.contains(Weather.getAddress()[1])) {
							ccode = text.split(",")[1];
						}
					}
					break;
				}
				event = parser.next();
			}

			if (!"".equals(ccode)) {
				return ccode;
			}
		}
		return "1509";

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.sasu.webservice.impl.NewsService#getSCityCode()
	 */
	@Override
	public String getSCityCode() throws Exception {
		String scode = "";
		getCity();
		String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getRegionProvince";
		HttpURLConnection connection = (HttpURLConnection) new java.net.URL(url)
				.openConnection();

		connection.setRequestMethod("GET");
		connection.setDoInput(true);
		connection.setDoOutput(true);

		connection.setDoInput(true);
		connection.setDoOutput(true);

		if (connection.getResponseCode() == 200) {
			InputStream inStream = connection.getInputStream();

			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(inStream, "UTF-8");
			int event = parser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {
				case XmlPullParser.START_TAG:
					if ("string".equals(parser.getName())) {
						String text = parser.nextText();
						if (text.contains(Weather.getAddress()[0])) {

							scode = text.split(",")[1];
						}
					}
					break;
				}
				event = parser.next();
			}

			if (!"".equals(scode)) {
				return scode;
			}

		}
		return "31123";

	}

	
	
	@SuppressWarnings("unused")
	private String getWebIp(String strUrl) {
		try {
		 
		 
		URL url = new URL(strUrl);
		BufferedReader br = new BufferedReader(new InputStreamReader(url
		.openStream()));
		String s = "";
		StringBuffer sb = new StringBuffer("");
		String webContent = "";
		while ((s = br.readLine()) != null) {
		sb.append(s + "rn");
		}
		 
		 
		br.close();
		webContent = sb.toString();
		int start = webContent.indexOf("[") + 1;
		int end = webContent.indexOf("]");
		System.out.println("webContent=" + webContent);
		System.out.println("start=" + start);
		System.out.println("end=" + end);
		if (start < 0 || end < 0) {
		return null;
		}
		webContent = webContent.substring(start, end);
		return webContent;
		 
		 
		} catch (Exception e) {
		e.printStackTrace();
		return "error open url:" + strUrl;
		 
		 
		}
	}
	
	/**
	 * 获得城市的中文名称
	 * 
	 * @return 四川 达州
	 * @throws Exception
	 */
	private String getCity() throws Exception {
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress().toString();// 获得本机IP
		// String address = addr.getHostName();// 获得本机名称
		// String ip = "220.181.38.49";//这是一个背景的地址
		
		if("127.0.0.1".equals(ip)){
			ip = "111.9.237.103";
		} 
		
		String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + ip;// 新浪的接口
		
		HttpURLConnection connection = (HttpURLConnection) new java.net.URL(url)
				.openConnection();

		connection.setRequestMethod("GET");
		connection.setDoInput(true);
		connection.setDoOutput(true);

		connection.setDoInput(true);
		connection.setDoOutput(true);

		ByteArrayOutputStream osStream = new ByteArrayOutputStream();

		if (connection.getResponseCode() == 200) {
			InputStream inStream = connection.getInputStream();

			int len = 0;
			byte[] b = new byte[1024];
			while ((len = inStream.read(b)) != -1) {
				osStream.write(b, 0, len);
			}
		}

		String s = new String(osStream.toByteArray(), "UTF-8");
		String result = weatherUtil.decodeUnicode(s);
		try {
			Weather.setAddress(weatherUtil.parseWeather(result).split(" "));
			return weatherUtil.parseWeather(result);
		} catch (Exception e) {
			Weather.setAddress("四川 达州".split(" "));
			return "四川 达州";
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.edu.sasu.webservice.impl.NewsService#resquestWeather()
	 */
	@Override
	public String[] resquestWeather() throws Exception {
		String ccode = getCCityCode();
		
		String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode="
				+ ccode + "&theUserID=db5339a04b3b4a988c0614f612822fe8";// 没有给定用户，代表我们是通过免费的用户去获取天气，（每天都有固定数量的免费访问次数）
		HttpURLConnection connection = (HttpURLConnection) new java.net.URL(url)
				.openConnection();

		connection.setRequestMethod("GET");
		connection.setDoInput(true);
		connection.setDoOutput(true);

		connection.setDoInput(true);
		connection.setDoOutput(true);

		String[] weather = new String[42];
		if (connection.getResponseCode() == 200) {
			InputStream inStream = connection.getInputStream();

			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(inStream, "UTF-8");
			int event = parser.getEventType();

			int i = 0;

			while (event != XmlPullParser.END_DOCUMENT) {
				switch (event) {
				case XmlPullParser.START_TAG:
					if ("string".equals(parser.getName()))
						weather[i++] = parser.nextText();
				}
				event = parser.next();
			}
			Weather.setWeatherInfo(weather);

		}
		return weather;
	}

}
